<template>
  <view class="checkin-container">
    <!-- 顶部信息 -->
    <view class="point-info-card">
      <view class="plan-name" v-if="planName && planName !== 'undefined'">{{ planName }}</view>
      <view class="point-name">{{ pointInfo.name }}</view>
      <view class="point-code">编号：{{ pointInfo.code }}</view>
      <view class="point-location">位置：{{ pointInfo.location }}</view>
    </view>
    
    <!-- 拍照区域 -->
    <view class="photo-section">
      <view class="section-title">巡检照片</view>
      <view class="photo-area">
        <view v-if="photos.length > 0" class="photo-item">
          <image :src="photos[0]" mode="aspectFill" class="photo-preview" @click="previewImage(0)"></image>
          <view class="delete-icon" @click="deletePhoto(0)">×</view>
        </view>
        <view class="photo-add" @click="takePhoto" v-if="photos.length === 0">
          <view class="add-icon">+</view>
          <view class="add-text">拍照</view>
        </view>
      </view>
    </view>
    
    <!-- 巡检结果 -->
    <view class="result-section">
      <view class="section-title">巡检结果</view>
      <view class="result-options">
        <view 
          v-for="(option, index) in resultOptions" 
          :key="index"
          :class="['result-option', selectedResult === option.value ? 'selected' : '']"
          @click="selectedResult = option.value"
        >{{ option.label }}</view>
      </view>
    </view>
    
    <!-- 备注 -->
    <view class="remark-section">
      <view class="section-title">备注</view>
      <textarea class="remark-input" v-model="remark" placeholder="请输入巡检备注信息（选填）" maxlength="200"></textarea>
      <view class="word-count">{{ remark.length }}/200</view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="cancel-btn" @click="goBack">取消</button>
      <button class="submit-btn" @click="submitCheckin">提交打卡</button>
    </view>
  </view>
</template>

<script>
import request from '@/util/request.js';

export default {
  name: 'PatrolCheckin',
  data() {
    return {
      pointId: null,
      taskId: null,
      planName: '',
      pointInfo: {
        name: '',
        code: '',
        location: '',
        category: '',
      },
      photos: [],
      resultOptions: [
        { label: '正常', value: 'normal' },
        { label: '异常', value: 'abnormal' }
      ],
      selectedResult: 'normal',
      remark: '',
      // 巡更进度信息
      progress: 0,
      totalCount: 0,
      checkedCount: 0
    }
  },
  methods: {
    async fetchPointInfo() {
      if (!this.pointId || !this.taskId) return;
      try {
        const res = await request({
          url: `patrol-server/patrolPoint/detail?pointId=${this.pointId}&taskId=${this.taskId}`,
          method: 'GET'
        });
        if (res && res.data) {
          this.pointInfo = res.data;
        }
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' });
      }
    },
    takePhoto() {
      uni.chooseImage({
        count: 1, // 限制只能选择一张图片
        sizeType: ['compressed'],
        sourceType: ['camera'],
        success: (res) => {
          // 清空之前的照片，只保留当前拍摄的照片
          this.photos = [res.tempFilePaths[0]];
        },
        fail: () => {
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          });
        }
      });
    },
    previewImage(index) {
      uni.previewImage({
        urls: this.photos,
        current: this.photos[index]
      });
    },
    deletePhoto(index) {
      this.photos.splice(index, 1);
    },
    goBack() {
      uni.navigateBack();
    },
    async submitCheckin() {
      // 表单验证
      if (this.photos.length === 0) {
        uni.showToast({
          title: '请拍摄巡检照片',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({ title: '提交中...' });
      
      try {
        // 获取位置信息
        let location = null;
        try {
          location = await new Promise((resolve, reject) => {
            uni.getLocation({
              type: 'gcj02',
              success: resolve,
              fail: reject
            });
          });
        } catch (err) {
          console.error('获取位置信息失败', err);
        }
        
        // 获取当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const checkTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        
        // 一次性上传数据和图片
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: request.baseUrl + 'patrol-server/patrolTask/checkinWithPhoto',
            filePath: this.photos[0],
            name: 'photo',  // 文件参数名
            formData: {
              pointId: this.pointId,
              taskId: this.taskId,
              result: this.selectedResult,
              remark: this.remark,
              checkTime: checkTime,
              latitude: location ? location.latitude : '',
              longitude: location ? location.longitude : '',
              // 传递巡更进度信息
              progress: this.progress,
              totalCount: this.totalCount,
              checkedCount: this.checkedCount
            },
            header: {
              'token': uni.getStorageSync('token')
            },
            success: (res) => {
              try {
                const data = JSON.parse(res.data);
                console.log('打卡接口返回数据:', data); // 添加日志查看返回值
                if (data.code === 200) { // 兼容不同的成功状态码
                  uni.showToast({
                    title: '打卡成功',
                    icon: 'success'
                  });
                  
                  // 延迟执行，等待提示显示完毕
                  // 记录当前任务ID，以确保在回调中能访问到
                  const currentTaskId = this.taskId;
                  console.log('准备转跳，当前taskId:', currentTaskId);
                  
                  setTimeout(() => {
                    try {
                      // 获取当前页面栈
                      const pages = getCurrentPages();
                      console.log('当前页面栈:', pages.length, '个页面');
                      
                      // 如果存在巡更详情页（上一页）
                      if (pages.length >= 2) {
                        console.log('检测到有上一页，准备返回');
                        // 直接返回上一页
                        uni.navigateBack({
                          delta: 1,
                          success: () => {
                            console.log('导航返回成功');
                            // 通知巡更详情页刷新数据
                            setTimeout(() => {
                              try {
                                const currentPages = getCurrentPages();
                                const currentPage = currentPages[currentPages.length - 1];
                                console.log('当前页面是否有fetchDetail方法:', !!currentPage.fetchDetail);
                                if (currentPage && currentPage.fetchDetail) {
                                  currentPage.fetchDetail();
                                }
                              } catch (err) {
                                console.error('刷新详情出错:', err);
                              }
                            }, 500);
                          },
                          fail: (err) => {
                            console.error('导航返回失败:', err);
                            // 导航失败，直接跳转
                            uni.redirectTo({
                              url: `/pages/patrol/detail?taskId=${currentTaskId}`
                            });
                          }
                        });
                      } else {
                        console.log('没有检测到上一页，直接跳转到详情页');
                        // 如果不存在上一页，则跳转到巡更任务详情页
                        uni.redirectTo({
                          url: `/pages/patrol/detail?taskId=${currentTaskId}`
                        });
                      }
                    } catch (err) {
                      console.error('页面转跳错误:', err);
                      // 出现异常时的兜底方案
                      uni.redirectTo({
                        url: `/pages/patrol/detail?taskId=${currentTaskId}`
                      });
                    }
                  }, 800);
                } else {
                  uni.showToast({
                    title: data.msg || '打卡失败',
                    icon: 'none'
                  });
                }
              } catch (e) {
                console.error('解析响应数据出错:', e);
                reject(new Error('解析响应失败'));
              }
            },
            fail: (err) => {
              console.error('上传请求失败:', err);
              reject(err);
            },
            complete: () => {
              uni.hideLoading();
            }
          });
        });
      } catch (e) {
        console.error('提交打卡失败', e);
        uni.hideLoading();
        uni.showToast({
          title: '打卡失败',
          icon: 'none'
        });
      }
    },
    async uploadImages() {
      if (!this.photos.length) return [];
      
      // 显示上传进度
      uni.showLoading({ title: '上传图片中...' });
      
      try {
        // 由于只有一张图片，直接上传
        const filePath = this.photos[0];
        
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: request.baseUrl + 'upload/image',
            filePath: filePath,
            name: 'file',
            // 添加token等认证信息
            header: {
              'Authorization': uni.getStorageSync('jwt')
            },
            success: (res) => {
              try {
                const data = JSON.parse(res.data);
                if (data.code === 0 && data.data) {
                  // 返回单张图片的URL
                  resolve([data.data.url]);
                } else {
                  reject(new Error(data.msg || '上传失败'));
                }
              } catch (e) {
                reject(new Error('解析响应失败'));
              }
            },
            fail: (err) => {
              reject(err);
            }
          });
        });
      } catch (e) {
        uni.hideLoading();
        uni.showToast({
          title: '图片上传失败: ' + (e.message || '未知错误'),
          icon: 'none',
          duration: 2000
        });
        throw e;
      } finally {
        uni.hideLoading(); // 确保上传结束后隐藏加载提示
      }
    }
  },
  onLoad(options) {
    this.pointId = options.pointId;
    this.taskId = options.taskId;
    
    // 如果URL参数中包含点位信息，则直接使用
    if (options.pointName && options.pointCode && options.pointLocation) {
      this.pointInfo = {
        name: decodeURIComponent(options.pointName),
        code: decodeURIComponent(options.pointCode),
        location: decodeURIComponent(options.pointLocation)
      };
    } else {
      // 否则从API获取
      this.fetchPointInfo();
    }
    
    // 设置计划名称
    if (options.planName) {
      this.planName = decodeURIComponent(options.planName);
    }
    
    // 设置巡更进度信息
    if (options.progress) {
      this.progress = Number(options.progress) || 0;
    }
    if (options.totalCount) {
      this.totalCount = Number(options.totalCount) || 0;
    }
    if (options.checkedCount) {
      this.checkedCount = Number(options.checkedCount) || 0;
    }
  }
}
</script>

<style scoped>
.checkin-container {
  background: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}
.point-info-card {
  background: #fff;
  margin: 24rpx;
  padding: 28rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #e6e6e6;
}
.plan-name {
  font-size: 28rpx;
  color: #1a7cf7;
  margin-bottom: 8rpx;
}
.point-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 12rpx;
}
.point-code, .point-location {
  font-size: 26rpx;
  color: #666;
  margin-top: 8rpx;
}
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 24rpx;
}
.photo-section, .result-section, .remark-section {
  background: #fff;
  margin: 24rpx;
  padding: 28rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #e6e6e6;
}
.photo-area {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}
.photo-item, .photo-add {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  position: relative;
}
.photo-preview {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}
.delete-icon {
  position: absolute;
  right: -16rpx;
  top: -16rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0,0,0,0.6);
  color: #fff;
  border-radius: 50%;
  text-align: center;
  line-height: 36rpx;
  font-size: 32rpx;
}
.photo-add {
  background: #f0f0f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.add-icon {
  font-size: 60rpx;
  color: #999;
  line-height: 1;
  margin-bottom: 8rpx;
}
.add-text {
  font-size: 24rpx;
  color: #999;
}
.result-options {
  display: flex;
  gap: 24rpx;
}
.result-option {
  padding: 16rpx 40rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
}
.result-option.selected {
  background: #1a7cf7;
  color: #fff;
  border-color: #1a7cf7;
}
.remark-input {
  width: 100%;
  height: 200rpx;
  background: #f7f7f7;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}
.word-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}
.bottom-actions {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  background: #fff;
  padding: 20rpx 24rpx;
  box-shadow: 0 -2rpx 8rpx #e6e6e6;
}
.cancel-btn, .submit-btn {
  width: 45%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: 500;
}
.cancel-btn {
  background: #f0f0f0;
  color: #666;
}
.submit-btn {
  background: #1a7cf7;
  color: #fff;
}
</style> 